package models

import (
	"time"
)

type DataAccessObject interface {

	CheckPasswd(user User) (bool, error)

	GetAllUsers(limit int, start ...int) ([]User, int64,  error)
	PutUser(user User) (int64, error)
	UpdateUser(id int64,user User) (int64, error)
	DeleteUser(id int64) (int64, error)
	GetUserByID(userID int64) ( User, bool, error)

	GetUserInfo(userID int64, limit int, start ... int) ( []UserInfo,  error)
	GetDBName() string
}

var g_db DataAccessObject=nil;
type Date time.Time
const (
	dateFormart = "2006-01-02"
)

func (t *Date) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+dateFormart+`"`, string(data), time.Local)
	*t = Date(now)
	return
}

func (t Date) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(dateFormart)+2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, dateFormart)
	b = append(b, '"')
	return b, nil
}

func (t Date) String() string {
	return time.Time(t).Format(dateFormart)
}

type Time time.Time

const (
	timeFormart = "2006-01-02 15:04:05"
)

func (t *Time) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), time.Local)
	*t = Time(now)
	return
}

func (t Time) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(timeFormart)+2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, timeFormart)
	b = append(b, '"')
	return b, nil
}

func (t Time) String() string {
	return time.Time(t).Format(timeFormart)
}

func GetDBAdapter() (db DataAccessObject){
	return g_db;
}
func RegisterAdapter(db DataAccessObject) {
	if db == nil {
		panic("store: Register adapter is nil")
	}
	if g_db != nil {
		panic("store: adapter '" + g_db.GetDBName() + "' is already registered")
	}
	g_db = db
}